package ui.fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fy.fyzf.R;
import com.fy.fyzf.base.BaseFragment;
import com.fy.fyzf.bean.AddSignOne;
import com.fy.fyzf.bean.HousesListBean;
import com.fy.fyzf.bean.PassengerNumberBean;
import com.fy.fyzf.bean.BaseData;
import com.fy.fyzf.bean.SaveBean;
import com.fy.fyzf.bean.SignDetailBean;
import com.fy.fyzf.dialog.LoopViewPopwindow;
import com.fy.fyzf.presenter.AddSignPresenter;
import com.fy.fyzf.utils.AppUtils;
import com.fy.fyzf.utils.MathUtils;
import com.fy.fyzf.utils.SPUtils;
import com.fy.fyzf.view.AddSignCallback;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import ui.activity.AllHousingActivity;
import ui.activity.SignStepActivity;
import ui.adapter.CheckBoxAdapter;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link StepOneFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class StepOneFragment extends BaseFragment<AddSignPresenter> implements AddSignCallback {

    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.rb3)
    RadioButton rb3;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_number_passenger)
    TextView tvNumberPassenger;
    @BindView(R.id.tv_number_housing)
    TextView tvNumberHousing;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.et_counselor)
    EditText etCounselor;
    @BindView(R.id.tv_conpany)
    TextView tvConpany;
    @BindView(R.id.tv_staff_name)
    TextView tvStaffName;
    @BindView(R.id.recycleView1)
    RecyclerView recycleView1;
    @BindView(R.id.recycleView2)
    RecyclerView recycleView2;
    @BindView(R.id.et_area)
    EditText etArea;
    @BindView(R.id.tv_ok)
    TextView tvOk;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "customersId";
    private static final String ARG_PARAM2 = "performanceId";
    private static final String TYPE = "type";

    // TODO: Rename and change types of parameters


    private CheckBoxAdapter checkBoxAdapter1;
    private CheckBoxAdapter checkBoxAdapter2;
    private AddSignOne addSignOne = new AddSignOne();

    private Integer clinchDealType = 1; //签约成交类型  默认第一个
    private Integer customersId;
    private int type;
    private Integer performanceId;
    private int signType;


    public StepOneFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static StepOneFragment newInstance(Integer param1, Integer param2,int i) {
        StepOneFragment fragment = new StepOneFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putInt(ARG_PARAM2, param2);
        args.putInt(TYPE, i);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            customersId = getArguments().getInt(ARG_PARAM1);
            performanceId = getArguments().getInt(ARG_PARAM2);
            signType = getArguments().getInt(TYPE);
        }
    }


    @Override
    protected AddSignPresenter createPresenter() {
        return new AddSignPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_step_one;
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.tv_date, R.id.tv_number_passenger, R.id.tv_search, R.id.tv_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_date:
                showDateDialog();
                break;
            case R.id.tv_number_passenger:
                mPresenter.getPassengerNumber();
                break;
            case R.id.tv_search:
                Intent intent = new Intent(getActivity(), AllHousingActivity.class);
                intent.putExtra("type", 2);
                startActivityForResult(intent, 10001);
                break;
            case R.id.tv_ok:
                addSignOne.setPropertyArea(etArea.getText().toString());
                if (TextUtils.isEmpty(tvDate.getText().toString())) {
                    AppUtils.showToast("请选择日期");
                    return;
                }

                if (TextUtils.isEmpty(tvNumberPassenger.getText().toString())) {
                    AppUtils.showToast("请选择客源");
                    return;
                }
                if (TextUtils.isEmpty(tvNumberHousing.getText().toString())) {
                    AppUtils.showToast("请选择房源");
                    return;
                }


                mPresenter.saveOneStep(addSignOne);
                break;
        }
    }

    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        checkBoxAdapter1 = new CheckBoxAdapter(getActivity());

        recycleView1.setLayoutManager(gridLayoutManager);
        recycleView1.setAdapter(checkBoxAdapter1);

        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 5) {
                    return 3;
                }
                return 1;
            }
        });
        checkBoxAdapter2 = new CheckBoxAdapter(getActivity());
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(getActivity(), 3);

        recycleView2.setLayoutManager(gridLayoutManager1);
        recycleView2.setAdapter(checkBoxAdapter2);
        gridLayoutManager1.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 5) {
                    return 3;
                }
                return 1;
            }
        });

        checkBoxAdapter1.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                checkBoxAdapter1.setSelect(position);
                addSignOne.setPropertyNature(String.valueOf(position + 1));
            }
        });

        checkBoxAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                checkBoxAdapter2.setSelect(position);
                addSignOne.setPropertyDecoration(String.valueOf(position + 1));
            }
        });

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb1) {
                    addSignOne.setClinchDealType(1);
                } else if (checkedId == R.id.rb2) {
                    addSignOne.setClinchDealType(2);

                } else {
                    addSignOne.setClinchDealType(3);
                }
            }
        });
    }

    @Override
    public void initData() {
        super.initData();


    }

    @Override
    protected void loadData() {
        List<String> list1 = new ArrayList<>(); //性质 propertyNature
        list1.add("公寓");
        list1.add("写字楼");
        list1.add("商铺");
        list1.add("工位");
        list1.add("花园");
        list1.add("其他");
        checkBoxAdapter1.setNewData(list1);

        List<String> list2 = new ArrayList<>(); //装修情况 propertyDecoration
        list2.add("全配");
        list2.add("简配");
        list2.add("豪华装修");
        list2.add("简单装修");
        list2.add("毛坯");
        list2.add("其他");
        checkBoxAdapter2.setNewData(list2);
        tvConpany.setText(SPUtils.getInstance(getActivity()).getString("company", ""));
        tvStaffName.setText(SPUtils.getInstance(getActivity()).getString("name", ""));

        /*if (signType == 1) {
            addSignOne.setPropertyNature("1");
            addSignOne.setPropertyDecoration("1");
            addSignOne.setClinchDealType(1);
        } else {
            mPresenter.getSingnContractdetail(performanceId);
        }*/
        mPresenter.getSingnContractdetail(performanceId);
    }

    @Override
    public void getPassengerNumberListSuccess(List<PassengerNumberBean> list) {
        List<String> titlts = new ArrayList<>();
        List<Integer> idS = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            titlts.add(list.get(i).getCustomerName() + "-" + list.get(i).getCustomerNumber());
            idS.add(list.get(i).getCustomerId());
        }
        LoopViewPopwindow loopViewPopwindow = new LoopViewPopwindow(getActivity());
        loopViewPopwindow.setIds(idS).setTitleData(titlts).setTitle(" ").showPop(etArea);
        loopViewPopwindow.getView(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvNumberPassenger.setText(titlts.get(loopViewPopwindow.position));
                loopViewPopwindow.dismiss();
            }
        });
    }

    @Override
    public void saveOneStepSuccess(BaseData baseData) {
        SaveBean saveBean = new Gson().fromJson(baseData.data.toString(), SaveBean.class);
        String s = MathUtils.rvZeroAndDot(saveBean.getPerformanceId());
        SPUtils.getInstance(getActivity()).putString("performanceId", s);
        SignStepActivity activity = (SignStepActivity) getActivity();
        activity.oneNext();
    }

    @Override
    public void saveTwoStepSuccess(BaseData baseData) {

    }

    @Override
    public void saveThreeStepSuccess(BaseData baseData) {

    }

    @Override
    public void getSingnContractdetail(SignDetailBean signContractDetailBean) {

        addSignOne.setClinchDealType(signContractDetailBean.getClinchDealType());
        addSignOne.setClosingDate(signContractDetailBean.getClosingDate());
        tvDate.setText(signContractDetailBean.getClosingDate());
        addSignOne.setHousingId(signContractDetailBean.getHousingId());
        tvNumberHousing.setText(signContractDetailBean.getHousingNo());
//        addSignOne.setPropertyConsultant(signContractDetailBean.getPropertyConsultant());
//        etCounselor.setText(signContractDetailBean.getPropertyConsultant());

        tvNumberPassenger.setText(signContractDetailBean.getCustomerNumber());
        addSignOne.setCustomersId(signContractDetailBean.getCustomersId());
        addSignOne.setPropertyNature(String.valueOf(signContractDetailBean.getPropertyNature()));
        checkBoxAdapter1.setSelect(Integer.parseInt(signContractDetailBean.getPropertyNature()) -1);
        addSignOne.setPropertyDecoration(signContractDetailBean.getPropertyDecoration());
        checkBoxAdapter2.setSelect(Integer.parseInt(signContractDetailBean.getPropertyDecoration()) -1);
        etArea.setText(signContractDetailBean.getPropertyArea());
        addSignOne.setPropertyArea(signContractDetailBean.getPropertyArea());
    }

    @Override
    public void exChangeSignContractSuccess(BaseData data) {

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void showDateDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                tvDate.setText(year + "-" + month + "-" + dayOfMonth);
                addSignOne.setClosingDate(tvDate.getText().toString() +" 00:00:00");
//                stringBuilderDate.append(year + "-" + month + "-" + dayOfMonth);
            }
        },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 10001) {
            HousesListBean.ListBean listBean = (HousesListBean.ListBean) data.getSerializableExtra("data");
            tvNumberHousing.setText(listBean.getAreaName() + "-" + listBean.getHousingNo());
            addSignOne.setCustomersId(customersId);
            addSignOne.setHousingId(listBean.getHousingId());
        }
    }
}